package handler

import (
	"fmt"
	"net"
	"sync"
	"sync/atomic"
	"time"

	"nettools/shared/models"
	"nettools/shared/protocol"
	"nettools/shared/utils"
)

// ConnectionManager 连接管理器
type ConnectionManager struct {
	// 连接计数器
	nextConnID   uint32
	nextClientID uint32

	// 客户端连接组管理 (clientID -> 客户端连接组)
	clientGroups map[string]*models.ClientConnectionGroup
	clientMutex  sync.RWMutex

	// 服务连接管理 (连接ID -> 服务连接)
	serviceConns map[uint32]*models.ServiceConnection
	serviceMutex sync.RWMutex

	// 代理连接管理 (连接ID -> 代理连接)
	proxyConns map[uint32]*models.ProxyConnection
	proxyMutex sync.RWMutex

	// 服务映射 (服务名 -> 端口)
	serviceMap map[string]int

	// 端口映射 (端口 -> 服务名)
	portMap   map[int]string
	portMutex sync.RWMutex

	// 配置
	maxConnections       int
	maxServicesPerClient int
	connTimeout          time.Duration

	// 统计信息
	stats      *models.ConnectionStats
	statsMutex sync.RWMutex

	// 监听器管理
	listeners map[string]net.Listener // 服务监听器
	services  map[string]*ServiceInfo // 服务信息

	// 客户端管理
	clients    map[string]*ClientConnection // 已连接的客户端
	clientsMux sync.RWMutex                 // 客户端锁

	// 会话管理
	sessions    map[string]*Session // 活动会话
	sessionsMux sync.RWMutex        // 会话锁

	// 控制通道
	stopChan chan struct{}
	wg       sync.WaitGroup
}

// ServiceInfo 服务信息
type ServiceInfo struct {
	Name        string
	Port        int
	ServiceType string // "proxy" 或 "management"
	Listener    net.Listener

	// 转发模式配置
	Remote     bool   // 是否为远程模式：true=通过客户端转发，false=直接转发到局域网
	TargetIP   string // 目标IP地址（remote=false时使用）
	TargetPort int    // 目标端口（remote=false时使用）
}

// ClientConnection 客户端连接
type ClientConnection struct {
	ID       string
	Conn     net.Conn
	Services map[string]*ClientService // 客户端提供的服务
	LastSeen time.Time
	mu       sync.RWMutex
}

// ClientService 客户端服务
type ClientService struct {
	Name       string
	ServerPort int
	TargetHost string
	TargetPort int
	Protocol   string
}

// Session 会话信息
type Session struct {
	ID          string
	ClientConn  net.Conn // 外部客户端连接
	ServiceName string
	TargetHost  string
	TargetPort  int
	CreatedAt   time.Time
}

// NewConnectionManager 创建连接管理器
func NewConnectionManager(maxConns, maxServicesPerClient int, connTimeout time.Duration) *ConnectionManager {
	return &ConnectionManager{
		clientGroups:         make(map[string]*models.ClientConnectionGroup),
		serviceConns:         make(map[uint32]*models.ServiceConnection),
		proxyConns:           make(map[uint32]*models.ProxyConnection),
		serviceMap:           make(map[string]int),
		portMap:              make(map[int]string),
		maxConnections:       maxConns,
		maxServicesPerClient: maxServicesPerClient,
		connTimeout:          connTimeout,
		stats: &models.ConnectionStats{
			ServiceStats: make(map[string]*models.ServiceStats),
		},
		listeners: make(map[string]net.Listener),
		services:  make(map[string]*ServiceInfo),
		clients:   make(map[string]*ClientConnection),
		sessions:  make(map[string]*Session),
		stopChan:  make(chan struct{}),
	}
}

// RegisterService 注册服务
func (cm *ConnectionManager) RegisterService(serviceName string, port int, serviceType string, remote bool, targetIP string, targetPort int) error {
	cm.serviceMutex.Lock()
	cm.portMutex.Lock()
	defer cm.serviceMutex.Unlock()
	defer cm.portMutex.Unlock()

	// 检查服务名称是否已存在
	if existingPort, exists := cm.serviceMap[serviceName]; exists {
		return fmt.Errorf("服务 '%s' 已存在，端口: %d", serviceName, existingPort)
	}

	// 检查端口是否已被使用
	if existingService, exists := cm.portMap[port]; exists {
		return fmt.Errorf("端口 %d 已被服务 '%s' 使用", port, existingService)
	}

	// 创建服务信息对象
	serviceInfo := &ServiceInfo{
		Name:        serviceName,
		Port:        port,
		ServiceType: serviceType,
		Listener:    nil, // 监听器将在StartListening中创建
		Remote:      remote,
		TargetIP:    targetIP,
		TargetPort:  targetPort,
	}

	// 注册服务
	cm.serviceMap[serviceName] = port
	cm.portMap[port] = serviceName
	cm.services[serviceName] = serviceInfo

	// 初始化服务统计
	cm.statsMutex.Lock()
	cm.stats.ServiceStats[serviceName] = &models.ServiceStats{
		ServiceName: serviceName,
		ServerPort:  port,
	}
	cm.statsMutex.Unlock()

	modeStr := "远程"
	if !remote {
		modeStr = fmt.Sprintf("直接转发(%s:%d)", targetIP, targetPort)
	}
	utils.Info("服务注册成功: %s -> 端口 %d (类型: %s, 模式: %s)", serviceName, port, serviceType, modeStr)
	return nil
}

// AddServiceConnection 添加服务连接 (内网客户端连接)
func (cm *ConnectionManager) AddServiceConnection(clientID, serviceName string, conn net.Conn) (*models.ServiceConnection, error) {
	// 获取服务端口
	cm.serviceMutex.RLock()
	serverPort, exists := cm.serviceMap[serviceName]
	cm.serviceMutex.RUnlock()

	if !exists {
		return nil, fmt.Errorf("服务 '%s' 不存在", serviceName)
	}

	// 检查客户端连接数限制
	cm.clientMutex.RLock()
	clientGroup, clientExists := cm.clientGroups[clientID]
	cm.clientMutex.RUnlock()

	if clientExists && len(clientGroup.Services) >= cm.maxServicesPerClient {
		return nil, fmt.Errorf("客户端 '%s' 服务连接数已达上限: %d", clientID, cm.maxServicesPerClient)
	}

	// 生成连接ID
	connID := atomic.AddUint32(&cm.nextConnID, 1)

	// 创建服务连接
	serviceConn := models.NewServiceConnection(connID, serviceName, serverPort, conn)

	// 添加到服务连接映射
	cm.serviceMutex.Lock()
	cm.serviceConns[connID] = serviceConn
	cm.serviceMutex.Unlock()

	// 添加到客户端连接组
	cm.clientMutex.Lock()
	if !clientExists {
		// 创建新的客户端连接组
		clientGroup = models.NewClientConnectionGroup(clientID, conn.RemoteAddr().String())
		cm.clientGroups[clientID] = clientGroup
	}
	clientGroup.AddServiceConnection(serviceConn)
	cm.clientMutex.Unlock()

	// 更新统计信息
	cm.updateServiceStats(serviceName, func(stats *models.ServiceStats) {
		stats.ActiveConnections++
		stats.TotalConnections++
		stats.LastActive = time.Now()
	})

	utils.Info("服务连接建立: 客户端=%s, 服务=%s, 连接ID=%d", clientID, serviceName, connID)
	return serviceConn, nil
}

// AddProxyConnection 添加代理连接 (外部客户端连接)
func (cm *ConnectionManager) AddProxyConnection(serviceName string, conn net.Conn) (*models.ProxyConnection, error) {
	// 查找对应的服务连接
	var serviceConn *models.ServiceConnection
	cm.serviceMutex.RLock()
	for _, sConn := range cm.serviceConns {
		if sConn.ServiceName == serviceName {
			serviceConn = sConn
			break
		}
	}
	cm.serviceMutex.RUnlock()

	if serviceConn == nil {
		return nil, fmt.Errorf("服务 '%s' 没有可用的客户端连接", serviceName)
	}

	// 生成连接ID
	connID := atomic.AddUint32(&cm.nextConnID, 1)

	// 创建代理连接
	proxyConn := models.NewProxyConnection(connID, conn, serviceConn.ID, serviceName, serviceConn.ServerPort)

	// 添加到代理连接映射
	cm.proxyMutex.Lock()
	cm.proxyConns[connID] = proxyConn
	cm.proxyMutex.Unlock()

	// 添加到服务连接的代理映射
	serviceConn.AddProxyConnection(proxyConn)

	// 更新统计信息
	cm.updateServiceStats(serviceName, func(stats *models.ServiceStats) {
		stats.ActiveConnections++
		stats.TotalConnections++
		stats.LastActive = time.Now()
	})

	utils.Info("代理连接建立: 服务=%s, 连接ID=%d, 关联服务连接=%d", serviceName, connID, serviceConn.ID)
	return proxyConn, nil
}

// RemoveServiceConnection 移除服务连接
func (cm *ConnectionManager) RemoveServiceConnection(connID uint32) error {
	cm.serviceMutex.Lock()
	serviceConn, exists := cm.serviceConns[connID]
	if exists {
		delete(cm.serviceConns, connID)
	}
	cm.serviceMutex.Unlock()

	if !exists {
		return fmt.Errorf("服务连接 %d 不存在", connID)
	}

	// 关闭连接
	serviceConn.Close()

	// 从客户端连接组中移除
	cm.clientMutex.Lock()
	for _, clientGroup := range cm.clientGroups {
		if _, exists := clientGroup.Services[serviceConn.ServiceName]; exists {
			clientGroup.RemoveServiceConnection(serviceConn.ServiceName)
			// 如果客户端组没有服务连接了，删除客户端组
			if len(clientGroup.Services) == 0 {
				delete(cm.clientGroups, clientGroup.ClientID)
			}
			break
		}
	}
	cm.clientMutex.Unlock()

	// 更新统计信息
	cm.updateServiceStats(serviceConn.ServiceName, func(stats *models.ServiceStats) {
		stats.ActiveConnections--
	})

	utils.Info("服务连接已移除: 连接ID=%d, 服务=%s", connID, serviceConn.ServiceName)
	return nil
}

// RemoveProxyConnection 移除代理连接
func (cm *ConnectionManager) RemoveProxyConnection(connID uint32) error {
	cm.proxyMutex.Lock()
	proxyConn, exists := cm.proxyConns[connID]
	if exists {
		delete(cm.proxyConns, connID)
	}
	cm.proxyMutex.Unlock()

	if !exists {
		return fmt.Errorf("代理连接 %d 不存在", connID)
	}

	// 关闭连接
	proxyConn.Close()

	// 从服务连接的代理映射中移除
	cm.serviceMutex.RLock()
	if serviceConn, exists := cm.serviceConns[proxyConn.ServiceConnID]; exists {
		serviceConn.RemoveProxyConnection(connID)
	}
	cm.serviceMutex.RUnlock()

	// 更新统计信息
	cm.updateServiceStats(proxyConn.ServiceName, func(stats *models.ServiceStats) {
		stats.ActiveConnections--
	})

	utils.Info("代理连接已移除: 连接ID=%d, 服务=%s", connID, proxyConn.ServiceName)
	return nil
}

// GetServiceConnection 获取服务连接
func (cm *ConnectionManager) GetServiceConnection(connID uint32) (*models.ServiceConnection, bool) {
	cm.serviceMutex.RLock()
	defer cm.serviceMutex.RUnlock()
	conn, exists := cm.serviceConns[connID]
	return conn, exists
}

// GetProxyConnection 获取代理连接
func (cm *ConnectionManager) GetProxyConnection(connID uint32) (*models.ProxyConnection, bool) {
	cm.proxyMutex.RLock()
	defer cm.proxyMutex.RUnlock()
	conn, exists := cm.proxyConns[connID]
	return conn, exists
}

// GetServiceByPort 根据端口获取服务名
func (cm *ConnectionManager) GetServiceByPort(port int) (string, bool) {
	cm.portMutex.RLock()
	defer cm.portMutex.RUnlock()
	serviceName, exists := cm.portMap[port]
	return serviceName, exists
}

// GetPortByService 根据服务名获取端口
func (cm *ConnectionManager) GetPortByService(serviceName string) (int, bool) {
	cm.serviceMutex.RLock()
	defer cm.serviceMutex.RUnlock()
	port, exists := cm.serviceMap[serviceName]
	return port, exists
}

// GetClientConnections 获取指定客户端的所有连接
func (cm *ConnectionManager) GetClientConnections(clientID string) (*models.ClientConnectionGroup, bool) {
	cm.clientMutex.RLock()
	defer cm.clientMutex.RUnlock()
	group, exists := cm.clientGroups[clientID]
	return group, exists
}

// GetServiceConnections 获取指定服务的所有连接
func (cm *ConnectionManager) GetServiceConnections(serviceName string) []*models.ServiceConnection {
	var connections []*models.ServiceConnection
	cm.serviceMutex.RLock()
	for _, conn := range cm.serviceConns {
		if conn.ServiceName == serviceName {
			connections = append(connections, conn)
		}
	}
	cm.serviceMutex.RUnlock()
	return connections
}

// GetStats 获取连接统计信息
func (cm *ConnectionManager) GetStats() *models.ConnectionStats {
	cm.statsMutex.RLock()
	defer cm.statsMutex.RUnlock()

	// 实时计算统计信息
	cm.serviceMutex.RLock()
	activeServiceConns := len(cm.serviceConns)
	cm.serviceMutex.RUnlock()

	cm.proxyMutex.RLock()
	activeProxyConns := len(cm.proxyConns)
	cm.proxyMutex.RUnlock()

	cm.clientMutex.RLock()
	activeClientGroups := len(cm.clientGroups)
	cm.clientMutex.RUnlock()

	// 更新统计信息
	stats := *cm.stats
	stats.ActiveServiceConnections = activeServiceConns
	stats.ActiveProxyConnections = activeProxyConns
	stats.ActiveClientGroups = activeClientGroups

	return &stats
}

// CleanupInactiveConnections 清理非活跃连接
func (cm *ConnectionManager) CleanupInactiveConnections(timeout time.Duration) {
	// 清理非活跃的服务连接
	cm.serviceMutex.RLock()
	var inactiveServiceConns []uint32
	for connID, conn := range cm.serviceConns {
		if !conn.IsActive(timeout) {
			inactiveServiceConns = append(inactiveServiceConns, connID)
		}
	}
	cm.serviceMutex.RUnlock()

	for _, connID := range inactiveServiceConns {
		cm.RemoveServiceConnection(connID)
		utils.Warn("清理非活跃服务连接: %d", connID)
	}

	// 清理非活跃的代理连接
	cm.proxyMutex.RLock()
	var inactiveProxyConns []uint32
	for connID, conn := range cm.proxyConns {
		if !conn.IsActive(timeout) {
			inactiveProxyConns = append(inactiveProxyConns, connID)
		}
	}
	cm.proxyMutex.RUnlock()

	for _, connID := range inactiveProxyConns {
		cm.RemoveProxyConnection(connID)
		utils.Warn("清理非活跃代理连接: %d", connID)
	}

	utils.Debug("连接清理完成: 服务连接=%d, 代理连接=%d", len(inactiveServiceConns), len(inactiveProxyConns))
}

// updateServiceStats 更新服务统计信息
func (cm *ConnectionManager) updateServiceStats(serviceName string, updateFunc func(*models.ServiceStats)) {
	cm.statsMutex.Lock()
	defer cm.statsMutex.Unlock()

	stats, exists := cm.stats.ServiceStats[serviceName]
	if !exists {
		stats = &models.ServiceStats{
			ServiceName: serviceName,
		}
		cm.stats.ServiceStats[serviceName] = stats
	}

	updateFunc(stats)
}

// Close 关闭连接管理器
func (cm *ConnectionManager) Close() error {
	utils.Info("关闭连接管理器...")

	// 发送停止信号
	close(cm.stopChan)

	// 关闭所有监听器
	for name, listener := range cm.listeners {
		utils.Info("关闭监听器: %s", name)
		listener.Close()
	}

	// 关闭所有服务连接
	cm.serviceMutex.Lock()
	for connID := range cm.serviceConns {
		cm.RemoveServiceConnection(connID)
	}
	cm.serviceMutex.Unlock()

	// 关闭所有代理连接
	cm.proxyMutex.Lock()
	for connID := range cm.proxyConns {
		cm.RemoveProxyConnection(connID)
	}
	cm.proxyMutex.Unlock()

	// 等待所有协程结束
	cm.wg.Wait()

	utils.Info("连接管理器已关闭")
	return nil
}

// StartListening 开始监听所有注册的服务
func (cm *ConnectionManager) StartListening(host string) error {
	for name, service := range cm.services {
		addr := fmt.Sprintf("%s:%d", host, service.Port)
		listener, err := net.Listen("tcp", addr)
		if err != nil {
			return fmt.Errorf("监听端口 %d 失败: %w", service.Port, err)
		}

		service.Listener = listener
		cm.listeners[name] = listener

		// 启动监听协程
		cm.wg.Add(1)
		go cm.handleServiceListener(name, service)

		utils.Info("开始监听服务: %s (地址: %s)", name, addr)
	}

	return nil
}

// handleServiceListener 处理服务监听
func (cm *ConnectionManager) handleServiceListener(serviceName string, service *ServiceInfo) {
	defer cm.wg.Done()

	for {
		select {
		case <-cm.stopChan:
			return
		default:
			conn, err := service.Listener.Accept()
			if err != nil {
				select {
				case <-cm.stopChan:
					return
				default:
					utils.Error("接受连接失败: %v", err)
					continue
				}
			}

			// 处理新连接
			cm.wg.Add(1)
			go cm.handleConnection(serviceName, service, conn)
		}
	}
}

// handleConnection 处理连接
func (cm *ConnectionManager) handleConnection(serviceName string, service *ServiceInfo, conn net.Conn) {
	defer cm.wg.Done()
	defer conn.Close()

	utils.Info("新连接: %s -> %s (服务: %s)", conn.RemoteAddr(), conn.LocalAddr(), serviceName)

	if service.ServiceType == "management" {
		// 管理端口：处理内网客户端连接
		cm.handleInternalClient(conn)
	} else {
		// 代理端口：处理外部用户连接
		cm.handleExternalConnection(serviceName, conn)
	}
}

// handleInternalClient 处理内网客户端连接
func (cm *ConnectionManager) handleInternalClient(conn net.Conn) {
	utils.Info("处理内网客户端连接: %s", conn.RemoteAddr())

	for {
		select {
		case <-cm.stopChan:
			return
		default:
			// 设置读取超时
			conn.SetReadDeadline(time.Now().Add(cm.connTimeout))

			msgType, data, err := protocol.ReadMessage(conn)
			if err != nil {
				utils.Error("读取客户端消息失败: %v", err)
				return
			}

			if err := cm.handleClientMessage(conn, msgType, data); err != nil {
				utils.Error("处理客户端消息失败: %v", err)
				return
			}
		}
	}
}

// handleClientMessage 处理客户端消息
func (cm *ConnectionManager) handleClientMessage(conn net.Conn, msgType uint8, data []byte) error {
	switch msgType {
	case protocol.MsgTypeRegister:
		return cm.handleClientRegister(conn, data)
	case protocol.MsgTypeHeartbeat:
		return cm.handleClientHeartbeat(conn, data)
	case protocol.MsgTypeData:
		return cm.handleClientData(conn, data)
	default:
		utils.Warn("未知消息类型: 0x%02x", msgType)
		return nil
	}
}

// handleClientRegister 处理客户端注册
func (cm *ConnectionManager) handleClientRegister(conn net.Conn, data []byte) error {
	var registerMsg protocol.RegisterMessage
	if err := protocol.ParseMessage(protocol.MsgTypeRegister, data, &registerMsg); err != nil {
		return fmt.Errorf("解析注册消息失败: %w", err)
	}

	utils.Info("客户端注册: ID=%s, 服务数量=%d", registerMsg.ClientID, len(registerMsg.Services))

	// 创建客户端连接对象
	client := &ClientConnection{
		ID:       registerMsg.ClientID,
		Conn:     conn,
		Services: make(map[string]*ClientService),
		LastSeen: time.Now(),
	}

	// 注册客户端服务
	for _, svc := range registerMsg.Services {
		client.Services[svc.Name] = &ClientService{
			Name:       svc.Name,
			ServerPort: svc.ServerPort,
			TargetHost: svc.TargetHost,
			TargetPort: svc.TargetPort,
			Protocol:   svc.Protocol,
		}
		utils.Info("注册客户端服务: %s (端口 %d -> %s:%d)",
			svc.Name, svc.ServerPort, svc.TargetHost, svc.TargetPort)
	}

	// 保存客户端连接
	cm.clientsMux.Lock()
	cm.clients[registerMsg.ClientID] = client
	cm.clientsMux.Unlock()

	// 发送注册成功响应
	response := protocol.ResponseMessage{
		Success: true,
		Message: "注册成功",
	}
	return protocol.WriteMessage(conn, protocol.MsgTypeResponse, response)
}

// handleClientHeartbeat 处理客户端心跳
func (cm *ConnectionManager) handleClientHeartbeat(conn net.Conn, data []byte) error {
	// 更新客户端最后活跃时间
	cm.clientsMux.Lock()
	for _, client := range cm.clients {
		if client.Conn == conn {
			client.LastSeen = time.Now()
			break
		}
	}
	cm.clientsMux.Unlock()

	// 回复心跳
	heartbeat := protocol.HeartbeatMessage{
		Timestamp: time.Now().Unix(),
	}
	return protocol.WriteMessage(conn, protocol.MsgTypeHeartbeat, heartbeat)
}

// handleClientData 处理客户端数据
func (cm *ConnectionManager) handleClientData(conn net.Conn, data []byte) error {
	var dataMsg protocol.DataMessage
	if err := protocol.ParseMessage(protocol.MsgTypeData, data, &dataMsg); err != nil {
		return fmt.Errorf("解析数据消息失败: %w", err)
	}

	// 查找对应的会话
	cm.sessionsMux.RLock()
	session, exists := cm.sessions[dataMsg.SessionID]
	cm.sessionsMux.RUnlock()

	if !exists {
		return fmt.Errorf("会话不存在: %s", dataMsg.SessionID)
	}

	// 转发数据到外部客户端
	_, err := session.ClientConn.Write(dataMsg.Data)
	return err
}

// handleExternalConnection 处理外部连接
func (cm *ConnectionManager) handleExternalConnection(serviceName string, conn net.Conn) {
	utils.Info("处理外部连接: %s -> 服务 %s", conn.RemoteAddr(), serviceName)

	// 获取服务信息
	service, exists := cm.services[serviceName]
	if !exists {
		utils.Error("服务 %s 不存在", serviceName)
		return
	}

	// 根据服务的Remote字段决定转发模式
	if service.Remote {
		// 远程模式：通过内网客户端转发
		cm.handleRemoteForward(serviceName, service, conn)
	} else {
		// 直接转发模式：直接转发到局域网目标
		cm.handleDirectForward(serviceName, service, conn)
	}
}

// handleRemoteForward 处理远程转发（通过内网客户端）
func (cm *ConnectionManager) handleRemoteForward(serviceName string, service *ServiceInfo, conn net.Conn) {
	// 查找提供此服务的内网客户端
	var targetClient *ClientConnection
	var targetService *ClientService

	cm.clientsMux.RLock()
	for _, client := range cm.clients {
		for _, clientSvc := range client.Services {
			if clientSvc.ServerPort == service.Port {
				targetClient = client
				targetService = clientSvc
				break
			}
		}
		if targetClient != nil {
			break
		}
	}
	cm.clientsMux.RUnlock()

	if targetClient == nil {
		utils.Error("未找到提供服务 %s 的内网客户端", serviceName)
		return
	}

	// 创建会话
	sessionID := fmt.Sprintf("%s-%d", serviceName, time.Now().UnixNano())
	session := &Session{
		ID:          sessionID,
		ClientConn:  conn,
		ServiceName: serviceName,
		TargetHost:  targetService.TargetHost,
		TargetPort:  targetService.TargetPort,
		CreatedAt:   time.Now(),
	}

	cm.sessionsMux.Lock()
	cm.sessions[sessionID] = session
	cm.sessionsMux.Unlock()

	utils.Info("创建远程转发会话: %s (%s -> %s:%d)",
		sessionID, serviceName, targetService.TargetHost, targetService.TargetPort)

	// 通知内网客户端建立连接
	connectMsg := protocol.ConnectMessage{
		SessionID:   sessionID,
		ServiceName: serviceName,
		TargetHost:  targetService.TargetHost,
		TargetPort:  targetService.TargetPort,
	}

	if err := protocol.WriteMessage(targetClient.Conn, protocol.MsgTypeConnect, connectMsg); err != nil {
		utils.Error("通知内网客户端失败: %v", err)
		return
	}

	// 开始转发外部连接的数据
	cm.forwardExternalData(sessionID, conn, targetClient.Conn)
}

// handleDirectForward 处理直接转发（直接连接局域网目标）
func (cm *ConnectionManager) handleDirectForward(serviceName string, service *ServiceInfo, clientConn net.Conn) {
	defer clientConn.Close()

	utils.Info("开始直接转发: %s -> %s:%d", serviceName, service.TargetIP, service.TargetPort)

	// 连接到目标地址
	targetAddr := fmt.Sprintf("%s:%d", service.TargetIP, service.TargetPort)
	targetConn, err := net.DialTimeout("tcp", targetAddr, 10*time.Second)
	if err != nil {
		utils.Error("连接目标地址失败: %v", err)
		return
	}
	defer targetConn.Close()

	utils.Info("✅ 已连接到目标地址: %s", targetAddr)

	// 创建会话记录
	sessionID := fmt.Sprintf("direct-%s-%d", serviceName, time.Now().UnixNano())
	session := &Session{
		ID:          sessionID,
		ClientConn:  clientConn,
		ServiceName: serviceName,
		TargetHost:  service.TargetIP,
		TargetPort:  service.TargetPort,
		CreatedAt:   time.Now(),
	}

	cm.sessionsMux.Lock()
	cm.sessions[sessionID] = session
	cm.sessionsMux.Unlock()

	utils.Info("创建直接转发会话: %s", sessionID)

	// 启动双向数据转发
	cm.startDirectBidirectionalForward(sessionID, clientConn, targetConn)
}

// startDirectBidirectionalForward 启动直接双向数据转发
func (cm *ConnectionManager) startDirectBidirectionalForward(sessionID string, clientConn, targetConn net.Conn) {
	defer func() {
		// 清理会话
		cm.sessionsMux.Lock()
		delete(cm.sessions, sessionID)
		cm.sessionsMux.Unlock()
		utils.Info("直接转发会话结束: %s", sessionID)
	}()

	// 创建错误通道用于任一方向转发失败时通知
	errChan := make(chan error, 2)

	// 启动客户端到目标的转发
	go func() {
		buffer := make([]byte, 32*1024) // 32KB 缓冲区
		for {
			n, err := clientConn.Read(buffer)
			if err != nil {
				errChan <- fmt.Errorf("客户端读取失败: %w", err)
				return
			}

			_, err = targetConn.Write(buffer[:n])
			if err != nil {
				errChan <- fmt.Errorf("目标写入失败: %w", err)
				return
			}
		}
	}()

	// 启动目标到客户端的转发
	go func() {
		buffer := make([]byte, 32*1024) // 32KB 缓冲区
		for {
			n, err := targetConn.Read(buffer)
			if err != nil {
				errChan <- fmt.Errorf("目标读取失败: %w", err)
				return
			}

			_, err = clientConn.Write(buffer[:n])
			if err != nil {
				errChan <- fmt.Errorf("客户端写入失败: %w", err)
				return
			}
		}
	}()

	// 等待任一方向转发结束
	err := <-errChan
	utils.Debug("直接转发结束: %v", err)
}

// forwardExternalData 转发外部连接数据
func (cm *ConnectionManager) forwardExternalData(sessionID string, clientConn, serverConn net.Conn) {
	defer func() {
		// 清理会话
		cm.sessionsMux.Lock()
		delete(cm.sessions, sessionID)
		cm.sessionsMux.Unlock()

		// 通知内网客户端断开连接
		disconnectMsg := protocol.ConnectMessage{SessionID: sessionID}
		protocol.WriteMessage(serverConn, protocol.MsgTypeDisconnect, disconnectMsg)
	}()

	buffer := make([]byte, 32*1024) // 32KB 缓冲区
	for {
		n, err := clientConn.Read(buffer)
		if err != nil {
			utils.Debug("外部连接读取结束: %v", err)
			return
		}

		// 转发数据到内网客户端
		dataMsg := protocol.DataMessage{
			SessionID: sessionID,
			Data:      buffer[:n],
		}

		if err := protocol.WriteMessage(serverConn, protocol.MsgTypeData, dataMsg); err != nil {
			utils.Error("转发数据到内网客户端失败: %v", err)
			return
		}
	}
}

// GetClientCount 获取客户端数量
func (cm *ConnectionManager) GetClientCount() int {
	cm.clientsMux.RLock()
	defer cm.clientsMux.RUnlock()
	return len(cm.clients)
}

// GetSessionCount 获取会话数量
func (cm *ConnectionManager) GetSessionCount() int {
	cm.sessionsMux.RLock()
	defer cm.sessionsMux.RUnlock()
	return len(cm.sessions)
}
